package com.jt.controller;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.jt.pojo.User;
import com.jt.service.SysUserService;
import com.jt.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisCluster;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/user/")
public class UserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private JedisCluster jedisCluster;

    @RequestMapping("/findUser")
    public List<User> findUser() {

        List<User> list = sysUserService.findObjects();
        return list;
    }

    /**
     * 检查注册用户名/电话/email是否被占用
     */
    @RequestMapping("check/{param}/{type}")
    public JSONPObject checkUser(@PathVariable String param, @PathVariable Integer type, String callback) {

        Boolean flag = sysUserService.checkUser(param, type);
        //int a = 1/0;
        return new JSONPObject(callback, SysResult.success(flag));
    }

    /**
     * url = "http://sso.jt.com/user/findUserById/"+userId
     *
     * @param param
     * @param type
     * @param callback
     * @return
     */
    @RequestMapping("findUserById/{userId}")
    public User checkUser(@PathVariable Long userId) {

        return sysUserService.findUserById(userId);
    }

    /**
     * 根据ticket信息查询用户的json信息 jsonp请求 返回值使用特定的对象封装
     * url : http://sso.jt.com/user/query/af08093d96df4f70967cfad7f494268f?callback=jsonp1600333074585&_=1600333074867
     */
    @RequestMapping("query/{ticket}")
    public JSONPObject findUserByTicket(@PathVariable String ticket, HttpServletResponse response, String callback) {

        if (jedisCluster.exists(ticket)) {
            //可以正确返回
            String userJSON = jedisCluster.get(ticket);
            return new JSONPObject(callback, SysResult.success(userJSON));
        } else {
            //如果根据ticket查询有误,则应该删除cookie信息
            Cookie cookie = new Cookie("JT_TICKET", "");
            cookie.setDomain("jt.com");
            cookie.setPath("/");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
            return new JSONPObject(callback, SysResult.fail());
        }
    }

}
